package at.jku.ssw.fortress.ui;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import org.eclipse.core.runtime.FileLocator;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.Platform;
import org.osgi.framework.Bundle;

public class UnicodeDatabase {

	public static class UnicodeMacro {
		public int unicode;
		public String name;
		public String category;
		
		public UnicodeMacro(int unicode, String name, String category) {
			super();
			this.unicode = unicode;
			this.name = name.replaceAll(" |-", "_");
			this.category = category;
		}
	}
	
	private List<UnicodeMacro> macros;
	private List<UnicodeMacro> alternativeMacros;

	public static final UnicodeDatabase INSTANCE = new UnicodeDatabase("UnicodeData.500.txt");
	
	private UnicodeDatabase(String file) {
		macros = new ArrayList<UnicodeMacro>();
		alternativeMacros = new ArrayList<UnicodeMacro>();
		try {
			Bundle plugin = Platform.getBundle(FortressPlugin.PLUGIN_ID);
			URL url = FileLocator.find(plugin, Path.fromOSString(file), null);
			BufferedReader r = new BufferedReader(new InputStreamReader(url.openStream()));

			String line;
			while ((line = r.readLine()) != null) {
				// split otherwise concats empty parts at the end
				line = line + ";END";
				String[] parts = line.split(";");
				String code = parts[0];
				int unicode = Integer.parseInt(code, 16);
				String name = parts[1];
				String category = parts[2];
				String alternativeName = parts[10];
				if(category.startsWith("C")) continue;
				macros.add(new UnicodeMacro(unicode, name, category));
				if(alternativeName != null && !"".equals(alternativeName)) {
					alternativeMacros.add(new UnicodeMacro(unicode, alternativeName, category));
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public UnicodeMacro[] getMacros() {
		return macros.toArray(new UnicodeMacro[0]);
	}
	
	public UnicodeMacro[] getAlternativeMacros() {
		return alternativeMacros.toArray(new UnicodeMacro[0]);
	}

}
